<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Nesk\Puphpeteer\Puppeteer;
use Illuminate\Support\Facades\Http;
use App\Models\MpWeixinCompany;
use App\Models\YiNew;
use DOMDocument;

class MakeMpCompany extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cc:mp-company';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $company = MpWeixinCompany::query()->whereNotNull("fakeid")->where("id",">=",27)->get();

        

        foreach($company as $k=>$v){

            
            $this->createToDeepNews($v['fakeid']);
            sleep(3);
             
        }
       // $queryUrl = "https://mp.weixin.qq.com/cgi-bin/appmsgpublish?sub=list&search_field=null&begin=0&count=5&query=&fakeid=MzA5NTI1MDEyNA==&type=101&free_publish_type=1&sub_action=list_ex&token=642733171&lang=zh_CN&f=json&ajax=1";

       



       

        
    }


    public function createToDeepNews($fakeid)
    {
        $queryUrl = "https://mp.weixin.qq.com/cgi-bin/appmsgpublish?sub=list&search_field=null&begin=40&count=20&query=&fakeid=".$fakeid."&type=101&free_publish_type=1&sub_action=list_ex&token=1915846676&lang=zh_CN&f=json&ajax=1";
         $user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)";

        $cookie = "appmsglist_action_3975454104=card; ua_id=L5dHsJWxbejJaCUkAAAAAE_ol4Gw8EnMqqah9usqddE=; wxuin=22579264596721; mm_lang=zh_CN; RK=qeuFu4Gjaz; ptcz=7e7fb728c92a7bd10c8714b2f69624cb8e26bc1726c204dcad7bd136cec9e119; pgv_pvid=4215038740; rand_info=CAESIILpIoFjvBPmQvDhlZDA8hf5TA9ykstF5Bk/NRi71FQp; slave_bizuin=3975454104; data_bizuin=3975454104; bizuin=3975454104; data_ticket=riqFONlvwITPVdZOjPm/VgXt/5srzVwwS8bfF/+WyzdHMrn91YUx4BgSwiVY7NLo; slave_sid=MkxYdlgyRTRCdFB0V18xVTFtWlYwQll6R3lNZmNSTVVrS1pFWkFJN2NZREhxbzVkcjQyc2RzdGFBc0w3QmZUcWx2NV95RmNWY29jdVVuVzRyaWRHZHZqcVJsN3lHRHk5RjdnX0N1WFhzQTk2ckJJakx0Tk80MmhTWGVCMU0zeUFHUm9KWnV5Z2xnZzV4S2ZO; slave_user=gh_6d7bbc3c44f2; xid=e22837d40a0aa79ad54c6db6d0d77aa7; _clck=3975454104|1|fu1|0; _clsk=1shd02a|1741435246198|3|1|mp.weixin.qq.com/weheat-agent/payload/record";
        $response = Http::withHeaders(['cookie' => $cookie,'user_agent'=>$user_agent])
                ->get($queryUrl);


        if ($response->successful()) {
            $dds = $response->json();

            $res = [];
            $data = [];

            if($dds['base_resp']['err_msg']=="ok"){
                $i=0;
                $list = json_decode($dds['publish_page'],true);
                foreach($list['publish_list'] as $k=>$v){

                    if($v['publish_info']){

                        $list['publish_list'][$k]['info'] = json_decode($v['publish_info'],true); 


                        foreach($list['publish_list'][$k]['info']['appmsgex'] as $kk=>$vv){
                           
                            $html = file_get_contents($vv['link']);
                            $dom = new DOMDocument();

                            libxml_use_internal_errors(true);
                            //$html = htmlspecialchars($html);
                            
                            
                            $dom->loadHTML('<?xml encoding="UTF-8">' . $html);

                            $sn = "";
                             if (preg_match('/var sn = \".*?\"/', $html, $matches)) {

                                $sn = str_replace("var sn =","",$matches[0]);
                                $sn =  str_replace('"',"",$sn);
                                $sn =  str_replace(' ',"",$sn);
                            }
                          
                            $elements = $dom->getElementsByTagName('div');
                            foreach($elements as $key=>$val){
                                $url = "";

                                if (strpos($val->getAttribute('id'), 'js_content') !== false) {
                                    //dd($dom->saveHTML($val));
                                    $data[$i]['content_cn'] = str_replace("data-src","src",$dom->saveHTML($val));

                                    $data[$i]['mp_biz'] = $fakeid;
                                    $data[$i]['mp_article_mid'] = $vv['appmsgid'];
                                    $data[$i]['mp_sn'] = $sn;
                                    $data[$i]['mp_idx'] = explode("_",$vv['aid'])[1];
                                    $data[$i]['title_cn'] = $vv['title'];
                                    $data[$i]['images'] = $vv['cover'];
                                    $data[$i]['url'] = $vv['link'];
                                    $data[$i]['started_at'] = date("Y-m-d H:i:s",$vv['create_time']);
                                    $data[$i]['created_at'] = date("Y-m-d H:i:s",time());
                                    $data[$i]['source'] = 'weixin';

                                    $i++;   

                                 }
                                  
                            }

                           
                           /* $finialResponse = Http::withHeaders(['cookie' => $cookie,'user_agent'=>$user_agent])->get($vv['link']);

                            if ($finialResponse->successful()) {
                                dd(123);
                                  $finialjson = $finialResponse->json();

                                  dd($finialjson);

                            }*/
                        }


                    }
                     
                }
               // dd($list);
                YiNew::insert($data);
               
            }
        }

    }

   
}
